<!--
 * 配置管理
 * @author luguoxiang
 * @date 2023-03-27
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <t-row :gutter="16" style="height: 100%">
    <t-col
      span="3"
      class="gl-table-container"
      style="background-color: var(--app-color-bg-primary); border-radius: var(--app-border-radius)"
    >
      <t-tree :data="tagList" hover activable :actived="selection" @active="onActive">
        <template #operations="{ node }">
          <edit-icon
            v-if="node.data.optUpdate"
            @click="updateTagBefore(node.data)"
          />
          <delete-icon
            v-if="node.data.optRemove"
            class="gl-ml"
            @click="removeTag(node)"
          />
        </template>
      </t-tree>
      <div class="gl-text-c">
        <t-link :underline="false" @click="updateRef.open({ scope: 0, createBy: user.id })">添加分组</t-link>
      </div>
    </t-col>
    <t-col span="9" class="gl-table-container">
      <lg-table :schema="schema" v-bind="tableProps">
        <!-- 工具栏 -->
        <template #toolbar-left>
          <btn-tool-add v-if="optMember" @click="userPickerRef.open()" />
          <btn-tool-remove v-if="optMember" @click="remove()" />
        </template>
        <!-- 操作栏 -->
        <template #actionbar="{ row }">
          <lg-button-list :limit="$RowBtnLimit">
            <btn-row-remove v-if="optMember" @click="remove(row.id)" />
          </lg-button-list>
        </template>
      </lg-table>
    </t-col>
  </t-row>
  <user-multiple-picker ref="userPickerRef" @ok="addUser" />
  <lg-modal ref="updateRef" v-slot="{ data }" header="分组设置" @confirm="updateTag">
    <t-form ref="formRef" :data="data" style="height: 45px">
      <t-form-item label="名称" name="name" :rules="rules.required('请输入名称')">
        <t-input v-model="data.name" />
      </t-form-item>
      <t-form-item label="可见范围" name="scope" :rules="rules.required('请输入名称')">
        <lg-dict
          v-if="!data.createBy || data.createBy === user.id"
          v-model="data.scope"
          code="UserTagOptTypeEnum"
          component="t-radio-group"
        />
        <lg-text v-else :model-value="data.scope" options="UserTagOptTypeEnum" />
      </t-form-item>
      <template v-if="data.scope === 1 && data.createBy === user.id">
        <t-form-item label="更新权限" name="optUpdate" :rules="rules.required('请输入名称')">
          <lg-dict v-model="data.optUpdate" code="UserTagOptTypeEnum" component="t-radio-group" />
        </t-form-item>
        <t-form-item label="删除权限" name="optRemove" :rules="rules.required('请输入名称')">
          <lg-dict v-model="data.optRemove" code="UserTagOptTypeEnum" component="t-radio-group" />
        </t-form-item>
        <t-form-item label="增减成员" name="optMember" :rules="rules.required('请输入名称')">
          <lg-dict v-model="data.optMember" code="UserTagOptTypeEnum" component="t-radio-group" />
        </t-form-item>
      </template>
    </t-form>
  </lg-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { DeleteIcon, EditIcon } from 'tdesign-icons-vue-next';
import userTagApi from '@/api/userTag';
import schema from './schema';
import { LgButtonList, LgTable, message, rules, useTable } from '@/soar';
import UserMultiplePicker from '@/pages/system/auth/user/Picker/MultiplePicker.vue';
import LgModal from '@/soar/components/LgModal/index.vue';
import LgDict from '@/soar/components/LgDict/index.vue';
import LgText from '@/soar/components/LgText/index.vue';
import { useAccountStore } from '@/store';

const userPickerRef = ref();
const updateRef = ref();
const formRef = ref();
const selection = ref([]);
const tagList = ref([]);

const { user } = useAccountStore();

const { remove, reload, tableProps } = useTable<any>({
  api: {
    ...userTagApi,
    query: (params: any) => {
      params.tagId = selection.value[0];
      return userTagApi.queryUser(params);
    },
    remove(userIds) {
      return userTagApi.removeUser(selection.value[0], userIds);
    },
  },
  props: {
    orderBys: ['id'],
    actionbar: {
      width: 100,
    },
    immediate: false,
  },
});

function load() {
  userTagApi.list().then((res) => {
    tagList.value = res.map((x) => ({
      value: x.id,
      label: x.name,
      createBy: x.createBy,
      optUpdate: x.createBy === user.id || x.optUpdate === 1,
      optRemove: x.createBy === user.id || x.optRemove === 1,
      optMember: x.createBy === user.id || x.optMember === 1,
    }));
    setTimeout(() => {
      onActive([tagList.value[0].value]);
    }, 500);
  });
}
load();

const optMember = ref(false);
function onActive(e) {
  if (e.length) {
    selection.value = e;
    const tag = tagList.value.find((x) => x.value === e[0]) || {};
    optMember.value = tag.optMember;
    reload(0);
  }
}

function addUser(e) {
  userTagApi.addUser({ mainId: selection.value[0], joinIds: e.map((x) => x.id) }).then(() => {
    reload(1);
  });
}

function updateTagBefore(data: any) {
  userTagApi.detail(data.value).then((res: any) => {
    res.scope = res.userId === '0' ? 1 : 0;
    updateRef.value.open(res);
  });
}

function updateTag({ e, data, close }) {
  formRef.value.validate().then((res: boolean) => {
    if (res === true) {
      data.userId = data.scope === 0 ? data.createBy : '0';
      userTagApi.saveOrUpdate(data, !!data.id).then(() => {
        load();
        close();
      });
    }
  });
}

function removeTag(e) {
  message.confirm(`确认删除“${e.label}”吗？`).then(() => {
    userTagApi.remove([e.value]).then(() => {
      load();
    });
  });
}
</script>
<style scoped lang="less"></style>
